<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增供应商报价"
    width="80%"
    destroy-on-close
  >
    <el-row :gutter="20">
      <!-- 左侧区域 -->
      <el-col :span="18">
        <el-form :model="form" label-width="120px" ref="formRef">
          <el-form-item label="产品名称">
            <el-input v-model="form.productName" disabled />
          </el-form-item>

          <el-form-item label="英文名称">
            <el-input v-model="form.productEnName" disabled />
          </el-form-item>

          <el-form-item label="产品规格">
            <el-input
              v-model="form.productSpec"
              type="textarea"
              :rows="3"
              disabled
            />
          </el-form-item>

          <el-form-item label="供应商编号">
            <el-select v-model="form.supplierCode" placeholder="请选择">
              <el-option
                v-for="item in supplierCodes"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="供应商名称">
            <el-input v-model="form.supplierName" />
          </el-form-item>

          <el-form-item label="供应商分类">
            <el-input v-model="form.supplierType" />
          </el-form-item>

          <el-form-item label="产品型号">
            <el-input v-model="form.model" />
          </el-form-item>

          <el-form-item label="数量">
    <el-row :gutter="10" style="width: 100%">
      <el-col :span="12">
        <el-input 
          v-model="form.num" 
          type="number" 
          min="0"
          step="0.01"
          @input="calculateAmount"
        />
      </el-col>
      <el-col :span="12">
        <el-select v-model="form.unit" placeholder="单位">
          <el-option label="kg" value="kg" />
          <el-option label="吨" value="ton" />
        </el-select>
      </el-col>
    </el-row>
  </el-form-item>

  <el-form-item label="单价">
    <el-input 
      v-model="form.price" 
      type="number" 
      min="0"
      step="0.01"
      @input="calculateAmount"
    />
  </el-form-item>

  <el-form-item label="总金额">
    <el-input 
      :value="formattedAmount" 
      type="text" 
      readonly 
      placeholder="0.00"
    />
  </el-form-item>

          <el-form-item label="报价有效期">
            <el-date-picker
              v-model="form.validity"
              type="date"
              placeholder="请选择日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </el-col>

      <!-- 右侧区域 -->
      <el-col :span="6" class="right-panel">
        <!-- 选择供应商按钮 -->
        <div class="choose-btn-box">
          <el-button type="primary"
          v-hasPermi="['business:supplier-info:query']" 
          @click="handleChooseSupplier"
          >
            选择供应商
          </el-button>
        </div>

        <!-- 底部按钮 -->
        <div class="footer-btns">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary"
          v-hasPermi="['business:supplier-info:query']" 
          @click="submitForm">确定</el-button>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
  <SupplierSelectDialog ref="supplierDialogRef" @select="handleSupplierSelected" />
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'  // 添加 watch 和 computed
import SupplierSelectDialog from './SupplierSelectDialog.vue'
import { SupplierInfoApi } from '@/api/product/supplierinfo/index'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { id } from 'element-plus/es/locale'

// 添加 emit 定义
const emit = defineEmits(['success'])
// const dialogVisible = ref(false)

const dialogVisible = ref(false)
const formRef = ref()
const supplierDialogRef = ref()
const currentProductId = ref<number | null>(null)
const currentSupplierId = ref<number | null>(null)

const type = ref<'create' | 'update'>('create')

// 添加计算属性格式化金额
const formattedAmount = computed(() => {
  if (form.amount === 0 || isNaN(form.amount)) {
    return '0.00';
  }
  return form.amount.toFixed(2);
});

const handleChooseSupplier = async () => {
  try {
    const res = await SupplierInfoApi.getSupplierInfoPage({ pageNo: 1, pageSize: 100 })
    
    // 处理响应数据
    let list = []
    
    if (res.data?.list) {
      list = res.data.list
    } else if (res.list) {
      list = res.list
    } else if (res.data?.data?.list) {
      list = res.data.data.list
    } else {
      list = res.data || []
    }
    
    console.log('供应商列表:', list)
    
    // 打开选择弹窗
    supplierDialogRef.value.open(list)
    
  } catch (err) {
    console.error('获取供应商信息失败:', err)
    let errorMsg = '获取供应商信息失败'
    if (err.response?.data?.message) {
      errorMsg += `: ${err.response.data.message}`
    } else if (err.message) {
      errorMsg += `: ${err.message}`
    }
    ElMessage.error(errorMsg)
  }
}

// 处理供应商选择事件
const handleSupplierSelected = (supplier) => {
  console.log('选中供应商:', supplier)
  
  // 自动填充表单字段
  form.supplierCode = supplier.code
  form.supplierName = supplier.name
  form.supplierType = supplier.supplierClassCode // 分类名称
  
  // 如果需要，可以填充更多字段
  // form.model = supplier.model || ''
  // form.country = supplier.country || ''
  
  // 自动选中对应的供应商编号
  if (!supplierCodes.value.includes(supplier.code)) {
    supplierCodes.value.push(supplier.code)
  }
  currentSupplierId.value = supplier.id // ✅ 保存供应商 ID
}

// 表单数据
const form = reactive({
  productName: '',
  productEnName: '',
  productSpec: '',
  supplierCode: '',
  supplierName: '',
  supplierType: '',
  model: '',
  num: 0,
  unit: '',
  price: 0,
  amount: 0,
  validity: ''
})
// 单独定义 id，确保它能正确更新
// 单独使用 ref 管理 id
const formId = ref(0)

// 供应商编号选项（动态更新）
const supplierCodes = ref(['SUP001', 'SUP002', 'SUP003'])

// 添加计算属性：自动计算总金额
// 添加计算属性：自动计算总金额
const calculateAmount = () => {
  // 确保数量和单价都是有效的数字
  const num = parseFloat(form.num);
  const price = parseFloat(form.price);
  
  // 如果数量和单价都是有效数字
  if (!isNaN(num) && !isNaN(price)) {
    // 计算总金额（保留2位小数）
    form.amount = parseFloat((num * price).toFixed(2));
  } else {
    // 如果输入无效，将总金额设为0
    form.amount = 0;
  }
  
  // 添加调试输出
  console.log('计算总金额:', {
    num: form.num,
    price: form.price,
    amount: form.amount
  });
}

// 监听数量和单价的变化
watch(
  () => [form.num, form.price],
  () => {
    calculateAmount();
  },
  { deep: true, immediate: true }
);

// 添加额外的监听器确保单位变化也会重新计算
watch(
  () => form.unit,
  () => {
    calculateAmount();
  }
);

const open = async (formType: 'create' | 'update', id?: number, productInfo?: any) => {
  console.log('=== OPEN 方法开始 ===')
  console.log('参数:', { formType, id, productInfo })
  dialogVisible.value = true // 使用 dialogVisible 替代 visible
  type.value = formType

  if (formType === 'update' && id) {
    console.log('进入更新模式，请求的 id:', id)
    // const res = await SupplierInfoApi.getQuoteDetail(id)
    // console.log('获取到的详情数据:', res)
  //   if (res) {
  //     formId.value = id
  //     Object.assign(form, res)
  //   currentSupplierId.value = res.supplierId  // ✅ 确保设置
  //   currentProductId.value = res.productId    // ✅ 如有必要也设置
  //   console.log('编辑模式，form.id:', form.id)
  //   console.log('编辑模式，id:', id)
  //   }
  // } else {
    // 新增时初始化数据
    if (productInfo) {
      Object.assign(form, {
        productName: productInfo.productName || '',
        productEnName: productInfo.productEnName || '',
        productSpec: productInfo.productSpec || '',
        supplierCode: productInfo.supplierCode || '',
        supplierName: productInfo.supplierName || '',
        supplierType: productInfo.supplierType || '',
        model: productInfo.model || '',
        num: productInfo.num || 0,
        unit: productInfo.unit || '',
        price: productInfo.price || 0,
        amount: productInfo.amount || 0,
        validity: productInfo.validity || ''
      })
      formId.value=id,
      currentSupplierId.value = productInfo.supplierId || null
      currentProductId.value = productInfo.productId || productInfo.id || null
    }
    
    console.log('编辑模式完成，formId.value:', formId.value)
  } else {
    // 新增时初始化数据
    Object.assign(form, {
      productName: productInfo?.productName || '',
      productEnName: productInfo?.productEnName || '',
      productSpec: productInfo?.productSpec || '',
      supplierCode: '',
      supplierName: '',
      supplierType: '',
      model: '',
      num: 0,
      unit: '',
      price: 0,
      amount: 0,
      validity: ''
    })
    formId.value = 0
    console.log('新增模式，formId.value 设置为 0')
    
    // 保存产品ID
    if (productInfo?.id) {
      currentProductId.value = productInfo.id
    }
  }
  
  console.log('=== OPEN 方法结束 ===')
  console.log('最终 formId.value:', formId.value)
}

/** 提交按钮 */
const submitForm = async () => {
  if (!form.supplierCode) {
    ElMessage.warning('请选择供应商')
    return
  }
  if (!form.price || form.price <= 0) {
    ElMessage.warning('请输入有效的单价')
    return
  }
  if (!form.num || form.num <= 0) {
    ElMessage.warning('请输入有效的数量')
    return
  }
  if (!currentProductId.value) {
    ElMessage.warning('未获取到产品ID')
    return
  }
  if (!currentSupplierId.value) {
    ElMessage.warning('未获取到供应商ID')
    return
  }
  // 确认 id 值
  console.log('提交前确认 formId.value:', formId.value)
  console.log('当前操作类型:', type.value)
  const data = {
    id: formId.value,  // 使用 formId.value 
    productId: currentProductId.value,
    supplierId: currentSupplierId.value,
    model: form.model,
    quantity: form.num,
    unit: form.unit,
    unitPrice: form.price,
    totalAmount: form.amount,
    validityDate: form.validity ? dayjs(form.validity).format('YYYY-MM-DD') : null,
    quoteDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  }
  console.log("即将发送的数据:", data)
  const loading = ElLoading.service({ text: '提交中...', lock: true })

  try {
    console.log("updateData:",data)

  const res = type.value === 'create'
    ? await SupplierInfoApi.addSupplierQuote(data)
    : await SupplierInfoApi.updateSupplierQuote(data)

  if (res) {
    ElMessage.success(type.value === 'create' ? '添加成功' : '修改成功')
    dialogVisible.value = false
    emit('success')
  } else {
    ElMessage.error(`提交失败：${res.msg}`)
  }
} catch (err) {
  ElMessage.error(`请求失败：${err.message}`)
} finally {
  loading.close()
}
}

defineExpose({ open })
</script>

<style scoped>
/* 样式保持不变 */
:deep(.el-input.is-disabled .el-input__inner),
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  background-color: #f5f5f5 !important;
  color: #606266;
  border: 1px solid #dcdfe6;
  cursor: not-allowed;
}

.right-panel {
  position: relative;
  min-height: 600px;
}

.choose-btn-box {
  margin-top: 132px;
  text-align: center;
}

.footer-btns {
  position: absolute;
  bottom: 20px;
  right: 20px;
}
/* 添加样式让总金额更突出 */
:deep(.el-input.is-readonly .el-input__inner) {
  font-weight: bold;
  color: #ff6a00;
  background-color: #fff8f0;
}

/* 添加样式让总金额更突出 */
/* 保持总金额样式不变，但去掉货币符号 */
:deep(.el-input.is-readonly .el-input__inner) {
  font-weight: bold;
  color: #ff6a00;
  background-color: #fff8f0;
  font-size: 16px;
}
</style>